package com.springcloud.market.stock.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springcloud.market.common.entity.Stock;
import com.springcloud.market.stock.mapper.StockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public abstract class StockService {

    @Autowired
    private StockMapper stockMapper;

    /**
     * 扣减库存
     * @param skuId 商品 ID
     * @param num   扣减数量
     * @return true-扣减成功；false-库存不足或商品不存在
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deduct(Long skuId, Integer num) {
        Stock stock = stockMapper.selectOne(
                new LambdaQueryWrapper<Stock>()
                        .eq(Stock::getSkuId, skuId));

        if (stock == null || stock.getCount() < num) {
            return false;          // 商品不存在或库存不足
        }

        stock.setCount(stock.getCount() - num);
        stockMapper.updateById(stock);
        return true;
    }

    @Transactional
    public abstract void reduce(Integer productId);
}